{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4bdb2a91-fa2a-4cee-ad5a-176cc957394d",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-23T12:15:28.171586Z",
     "start_time": "2024-05-23T12:15:28.076314Z"
    }
   },
   "outputs": [
    {
     "ename": "ModuleNotFoundError",
     "evalue": "No module named 'torch'",
     "output_type": "error",
     "traceback": [
      "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[0;31mModuleNotFoundError\u001B[0m                       Traceback (most recent call last)",
      "Cell \u001B[0;32mIn[1], line 1\u001B[0m\n\u001B[0;32m----> 1\u001B[0m \u001B[38;5;28;01mimport\u001B[39;00m \u001B[38;5;21;01mtorch\u001B[39;00m\n\u001B[1;32m      2\u001B[0m \u001B[38;5;28;01mimport\u001B[39;00m \u001B[38;5;21;01mtorch\u001B[39;00m\u001B[38;5;21;01m.\u001B[39;00m\u001B[38;5;21;01monnx\u001B[39;00m\n\u001B[1;32m      3\u001B[0m \u001B[38;5;28;01mimport\u001B[39;00m \u001B[38;5;21;01mtorchvision\u001B[39;00m\u001B[38;5;21;01m.\u001B[39;00m\u001B[38;5;21;01mmodels\u001B[39;00m \u001B[38;5;28;01mas\u001B[39;00m \u001B[38;5;21;01mmodels\u001B[39;00m\n",
      "\u001B[0;31mModuleNotFoundError\u001B[0m: No module named 'torch'"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import torch.onnx\n",
    "import torchvision.models as models\n",
    "import torchvision.transforms as transforms\n",
    "from PIL import Image\n",
    "import numpy as np\n",
    "from tests.config import TEST_MISC_DIR\n",
    "\n",
    "# Load pre-trained ResNet-50 model\n",
    "resnet = models.resnet50(pretrained=True)\n",
    "resnet = torch.nn.Sequential(*(list(resnet.children())[:-1]))  # Remove the last fully connected layer\n",
    "resnet.eval()\n",
    "\n",
    "# Define preprocessing transform\n",
    "preprocess = transforms.Compose([\n",
    "    transforms.Resize(256),\n",
    "    transforms.CenterCrop(224),\n",
    "    transforms.ToTensor(),\n",
    "    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n",
    "])\n",
    "\n",
    "# Load and preprocess the image\n",
    "def preprocess_image(image_path):\n",
    "    input_image = Image.open(image_path)\n",
    "    input_tensor = preprocess(input_image)\n",
    "    input_batch = input_tensor.unsqueeze(0)  # Add batch dimension\n",
    "    return input_batch\n",
    "\n",
    "# Example input for exporting\n",
    "input_image = preprocess_image('example.jpg')\n",
    "\n",
    "# Export the model to ONNX with dynamic axes\n",
    "torch.onnx.export(\n",
    "    resnet, \n",
    "    input_image, \n",
    "    \"model.onnx\", \n",
    "    export_params=True, \n",
    "    opset_version=9, \n",
    "    input_names=['input'], \n",
    "    output_names=['output'],\n",
    "    dynamic_axes={'input': {0: 'batch_size'}, 'output': {0: 'batch_size'}}\n",
    ")\n",
    "\n",
    "# Load ONNX model\n",
    "import onnx\n",
    "import onnxruntime as ort\n",
    "\n",
    "onnx_model = onnx.load(\"model.onnx\")\n",
    "ort_session = ort.InferenceSession(\"model.onnx\")\n",
    "\n",
    "# Run inference and extract feature vectors\n",
    "def extract_feature_vectors(image_paths):\n",
    "    input_images = [preprocess_image(image_path) for image_path in image_paths]\n",
    "    input_batch = torch.cat(input_images, dim=0)  # Combine images into a single batch\n",
    "    ort_inputs = {ort_session.get_inputs()[0].name: input_batch.numpy()}\n",
    "    ort_outs = ort_session.run(None, ort_inputs)\n",
    "    return ort_outs[0]\n",
    "\n",
    "# Example usage\n",
    "images = [TEST_MISC_DIR / \"image.jpeg\", str(TEST_MISC_DIR / \"small_image.jpeg\")]  # Replace with your image paths\n",
    "feature_vectors = extract_feature_vectors(images)\n",
    "print(\"Feature vector shape:\", feature_vectors.shape)\n"
   ]
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false
   },
   "id": "baa650c4cb3e0e6d"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
